package com.zjsystem.zjsy.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zjsystem.zjsy.constant.Constant;
import com.zjsystem.zjsy.dto.ZjxdAssignment;
import com.zjsystem.zjsy.enums.*;
import com.zjsystem.zjsy.mapper.ZjxdAssignmentMapper;
import com.zjsystem.zjsy.request.AssignmentRequest;
import com.zjsystem.zjsy.service.ZjxdAssignmentService;
import com.zjsystem.zjsy.vo.AuditVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wyf
 * @since 2024-07-11
 */
@Slf4j
@Service
public class ZjxdAssignmentServiceImpl extends ServiceImpl<ZjxdAssignmentMapper, ZjxdAssignment> implements ZjxdAssignmentService {
    @Resource
    private ZjxdAssignmentService assignmentService;

    /**
     * 新增
     * @param request
     */
    @Override
    public void saveAssignment(AssignmentRequest request) {
        log.info("任务新增入参为：{}", JSON.toJSONString(request));
        ZjxdAssignment zjxdAssignment = new ZjxdAssignment();
        String assignName = request.getAssignName();
        String assignValue = request.getAssignValue();
        String startTime = request.getAssignStartTime();
        String orgId = request.getSourceOrgId();
        String zzmb = request.getZzmb();
        if (StringUtils.isNotBlank(orgId)){
            zjxdAssignment.setSourceOrgId(orgId);
            zjxdAssignment.setSourceOrg(DeptEnums.valueOf(orgId).getDesc());
        }
        zjxdAssignment.setSourceTime(request.getSourceTime());
        //todo 假的 临时
        zjxdAssignment.setAssignStatus(AuditEnums.CJZ.name());
        zjxdAssignment.setAssignType(ZjStatusEnums.ZZRW.name());
        zjxdAssignment.setAssignName(assignName);
        zjxdAssignment.setAssignValue(assignValue);
        if (StringUtils.isNotBlank(startTime)){
            zjxdAssignment.setAssignStartTime(startTime);
        }

        zjxdAssignment.setCreateTime(new Date());
        zjxdAssignment.setUpdateTime(new Date());
        zjxdAssignment.setZzmb(zzmb);
        assignmentService.save(zjxdAssignment);
    }

    /**
     * 修改
     * @param request
     */
    @Override
    public void updateAssignment(AssignmentRequest request) {
        log.info("任务修改入参为：{}", JSON.toJSONString(request));
        Long id = Long.parseLong(request.getId());
        ZjxdAssignment ass = assignmentService.getById(id);
        if (ass.getAssignStatus().equals(AuditEnums.FBZ.name())){
            throw new RuntimeException("已发布不允许修改，谢谢合作");
        }
        ZjxdAssignment assignment = new ZjxdAssignment();
        assignment.setId(id);
        assignment.setAssignName(request.getAssignName());
        assignment.setAssignStatus(request.getAssignStatus());
        assignment.setSourceTime(request.getSourceTime());
        assignment.setAssignValue(request.getAssignValue());
        assignment.setAssignType(ZjStatusEnums.ZZRW.name());
        assignment.setAssignStartTime(request.getAssignStartTime());
        assignment.setSourceOrgId(request.getSourceOrgId());
        assignment.setZzmb(request.getZzmb());
        assignment.setCreateTime(new Date());
        assignment.setUpdateTime(new Date());
        assignmentService.update(assignment, Wrappers.<ZjxdAssignment>lambdaUpdate()
                .eq(ZjxdAssignment::getId,id));
    }

    @Override
    public IPage<ZjxdAssignment> getAssignment(AssignmentRequest request) {
        long num = request.getPage();
        long size = request.getSize();
        Page<ZjxdAssignment> page = new Page<>(num, size);
        String assignName = request.getAssignName();
        String status = request.getAssignStatus();
        IPage<ZjxdAssignment> assignment = null;
        LambdaQueryWrapper<ZjxdAssignment> qw = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(assignName)){
            qw.like(ZjxdAssignment::getAssignName,assignName);
        }
        if (StringUtils.isNotBlank(status)){
            qw.eq(ZjxdAssignment::getAssignStatus,status);
        }
        qw.eq(ZjxdAssignment::getLjsc, Constant.zero);
        // 获取N天内的数据
        Integer days = request.getTime();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.DAY_OF_YEAR, -days);
        Date agoDate = calendar.getTime();
        qw.ge(ZjxdAssignment::getCreateTime,agoDate);
        qw.orderByDesc(ZjxdAssignment::getUpdateTime);
        assignment = assignmentService.page(page, qw);
        List<ZjxdAssignment> list = assignment.getRecords();

        list.forEach(info -> info.setAssignType(ZjStatusEnums.valueOf(info.getAssignType()).getDesc()));
        return assignment;
    }

    @Override
    public Map<String, List<Map<String, String>>> getAll() {
        Map<String, List<Map<String, String>>> mapParam = new HashMap<>();

        List<Map<String, String>> deptList = new ArrayList<>();
        for (DeptEnums dept : DeptEnums.values()) {
            Map<String, String> stringMap = new HashMap<>();
            stringMap.put("name",dept.name());
            stringMap.put("desc",dept.getDesc());
            deptList.add(stringMap);
        }
        mapParam.put("dept", deptList);
        List<Map<String, String>> userList = new ArrayList<>();
        for (UserEnums user : UserEnums.values()) {
            Map<String, String> str = new HashMap<>();
            str.put("name",user.name());
            str.put("desc",user.getDesc());
            userList.add(str);
        }
        mapParam.put("zzmb", userList);

        List<Map<String, String>> statusList = new ArrayList<>();
        for (ZjStatusEnums status : ZjStatusEnums.values()) {
            Map<String, String> str = new HashMap<>();
            str.put("name",status.name());
            str.put("desc",status.getDesc());
            statusList.add(str);
        }
        mapParam.put("status", statusList);
        List<Map<String, String>> instructList = new ArrayList<>();
        for (InstructEnums instructEnums : InstructEnums.values()) {
            Map<String, String> str = new HashMap<>();
            str.put("name", instructEnums.name());
            str.put("desc", instructEnums.getDesc());
            instructList.add(str);
        }
        mapParam.put("ZL", instructList);
        List<Map<String, String>> dwList = new ArrayList<>();
        for (PlanDwEnums planDwEnums : PlanDwEnums.values()) {
            Map<String, String> stringMap = new HashMap<>();
            stringMap.put("name", planDwEnums.name());
            stringMap.put("desc", planDwEnums.getDesc());
            dwList.add(stringMap);
        }
        mapParam.put("DW", dwList);
        return mapParam;
    }

    @Override
    public List<AuditVO> getStageNum() {
        List<ZjxdAssignment> assignmentList = assignmentService.list();
        List<AuditVO> voList = new ArrayList<>();
        AuditVO vo = new AuditVO();
        vo.setCode("");
        vo.setDesc("所有");
        vo.setNumber(0);
        vo.setOrder(0);
        voList.add(vo);
        Map<String, List<ZjxdAssignment>> listMap = assignmentList.stream().collect(Collectors.groupingBy(a -> a.getAssignStatus()));
        listMap.forEach((type, info) -> {
            AuditVO auditVO = new AuditVO();
            auditVO.setCode(AuditEnums.valueOf(type).name());
            auditVO.setDesc(AuditEnums.valueOf(type).getDesc());
            auditVO.setNumber(info.size());
            if (type.equals(AuditEnums.CJZ.name())){
                auditVO.setOrder(1);
            }
            if (type.equals(AuditEnums.CHOUHUAZ.name())){
                auditVO.setOrder(2);
            }
            if (type.equals(AuditEnums.CEHAZ.name())){
                auditVO.setOrder(3);
            }
            if (type.equals(AuditEnums.FBZ.name())){
                auditVO.setOrder(4);
            }
            voList.add(auditVO);
        });
        List<AuditVO> collect = voList.stream().sorted(Comparator.comparing(AuditVO::getOrder)).collect(Collectors.toList());
        return collect;
    }

    private List<ZjxdAssignment> filterByDays(List<ZjxdAssignment> records, Integer days) {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_YEAR, -days);
        Date startDate = calendar.getTime();
        return records.stream().filter(info ->
                        info.getCreateTime().after(startDate))
                .sorted(Comparator.comparing(ZjxdAssignment::getUpdateTime).reversed()).collect(Collectors.toList());
    }
}
